<script setup lang="ts">
import { Search } from "@element-plus/icons-vue";
import axios from "axios";
import { ElButton, ElIcon } from "element-plus";
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import { router } from "../../router";
import type { Item } from "../../types/Book";
import type { ResultContext } from "../../types/ResultContext";
import LoginButton from "../login/LoginButton.vue";
const route = useRoute();
const activePath = ref(route.path);

// 每当 route.path（路由路径）发生变化时，就会执行回调。
// 把新的路径值 newPath 赋值给 activePath，确保 activePath 始终是当前路径。
watch(
  () => route.path,
  newPath => {
    activePath.value = newPath;
  },
);
// 页面跳转
function handleNavClick(path: string) {
  activePath.value = path;
  void router.push(path);
}

const keyword = ref("");
const showSuggestions = ref(false);
const suggestions = ref<Item[]>([]);

// 防抖定时器
let timer: number | undefined = undefined;

// 输入监听触发搜索建议（防抖）
watch(keyword, newVal => {
  fetchSuggestions(newVal);
});

// 获取搜索建议（防抖实现）
function fetchSuggestions(value: string) {
  clearTimeout(timer);
  const trimmed = value.trim();

  if (!trimmed) {
    suggestions.value = [];
    showSuggestions.value = false;
    return;
  }

  timer = window.setTimeout(async () => {
    try {
      const response = await axios.get<ResultContext<Item[]>>(
        "http://localhost:8080/api/books/suggestions",
        {
          params: { keyword: trimmed },
        },
      );
      suggestions.value = response.data.data;
      showSuggestions.value = suggestions.value.length > 0;
    } catch (_error) {
      suggestions.value = [];
      showSuggestions.value = false;
    }
  }, 300);
}

// 隐藏建议列表（延时处理避免失焦瞬间点击）
function hideSuggestions() {
  setTimeout(() => {
    showSuggestions.value = false;
  }, 100);
}

// 用户选择建议项
function selectSuggestion(item: { title: string; author: string }) {
  keyword.value = item.title;
  showSuggestions.value = false;
  doSearch();
}

// 执行跳转搜索
function doSearch() {
  const trimmed = keyword.value.trim();
  if (trimmed) {
    window.location.href = `/search?keyword=${encodeURIComponent(trimmed)}`;
  }
}
</script>

<template>
  <div class="top">
    <div class="logo myFlex-x">
      <img src="/img/logo.svg" alt="Logo" />
    </div>
    <div class="title myFlex-x" @click="handleNavClick('/')">湖大图书馆</div>
    <div
      class="home myFlex-x"
      :class="{ active: activePath === '/' }"
      @click="handleNavClick('/')"
    >
      首页
    </div>
    <div
      class="category myFlex-x"
      :class="{ active: activePath === '/category' }"
      @click="handleNavClick('/category')"
    >
      分类浏览
    </div>
    <div
      class="borrowing myFlex-x"
      :class="{ active: activePath === '/borrowing' }"
      @click="handleNavClick('/borrowing')"
    >
      我的借阅
    </div>
    <div
      class="collection myFlex-x"
      :class="{ active: activePath === '/collection' }"
      @click="handleNavClick('/collection')"
    >
      我的收藏
    </div>
    <div class="fill"></div>
    <div class="search-bar red-theme">
      <input
        v-model="keyword"
        @input="e => fetchSuggestions((e.target as HTMLInputElement).value)"
        @focus="showSuggestions = true"
        @blur="hideSuggestions"
        @keyup.enter="doSearch"
        placeholder="请输入书名、作者或ISBN"
      />
      <ElButton type="primary" circle @click="doSearch">
        <ElIcon><Search /></ElIcon>
      </ElButton>

      <ul v-if="showSuggestions && suggestions.length" class="suggestion-list">
        <li
          v-for="item in suggestions"
          :key="item.id"
          @mousedown.prevent="selectSuggestion(item)"
        >
          {{ item.title }} - {{ item.author }}
        </li>
      </ul>
    </div>

    <div class="personal myFlex-x">
      <LoginButton />
    </div>
  </div>
</template>

<style scoped>
.top {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  z-index: 1000;
  padding: 0 120px;
  box-sizing: border-box;
}

/* 子元素通用 */
.top > div {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  cursor: pointer;
  padding: 0 20px;
  box-sizing: border-box;
  border-radius: 25px;
  margin: 0 6px;
  transition: all 0.3s ease;
  font-weight: 500;
  color: #4a5568;
  position: relative;
}

/* logo和标题样式 */
.logo {
  cursor: default !important;
  padding: 0 8px !important;
  margin-right: 8px;
  background: none !important;
}

.logo img {
  width: 36px;
  height: 36px;
  filter: drop-shadow(0 2px 6px rgba(64, 158, 255, 0.3));
}

.title {
  margin-right: 50px;
  padding: 0 16px !important;
  font-size: 22px;
  font-weight: 700;
  color: #2d3748;
  background: linear-gradient(135deg, #409eff 0%, #53c0ff 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  cursor: pointer;
}

.title:hover {
  transform: scale(1.05);
}

/* 填充占满剩余空间 */
.fill {
  flex-grow: 1;
  cursor: default !important;
  background: none !important;
  margin: 0 !important;
  padding: 0 !important;
}

/* 菜单项样式 */
.home,
.category,
.borrowing,
.collection {
  min-width: 100px;
  font-size: 15px;
}

.personal {
  margin-left: 20px;
  background: none !important;
}

/* 激活状态样式 */
.active {
  background: linear-gradient(135deg, #409eff 0%, #53c0ff 100%) !important;
  color: white !important;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
}

/* hover样式 */
.home:hover,
.category:hover,
.borrowing:hover,
.collection:hover {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.2);
}

.active:hover {
  color: white !important;
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 1440px) {
  .top {
    padding: 0 60px;
  }
}

@media (max-width: 768px) {
  .top {
    padding: 0 20px;
    height: 70px;
  }

  .title {
    font-size: 18px;
    margin-right: 30px;
  }

  .home,
  .category,
  .borrowing,
  .collection {
    min-width: 70px;
    font-size: 14px;
    padding: 0 12px !important;
  }

  .top > div {
    height: 40px;
    margin: 0 3px;
  }
}

.search-bar {
  position: relative;
  display: flex;
  align-items: center;
  padding: 6px 10px;
  border-radius: 12px;
  background: #f5f7fa;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  min-width: 320px;
  max-width: 420px;
  transition: box-shadow 0.2s ease;
}

.search-bar input {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 8px;
  background-color: #fff;
  font-size: 14px;
  outline: none;
  transition: box-shadow 0.2s ease;
}

.search-bar input:focus {
  box-shadow: 0 0 0 2px #409eff;
}
.search-bar button {
  margin-left: 8px;
  padding: 8px 12px;
  border: none;
  background-color: #409eff;
  color: white;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.search-bar button:hover {
  background-color: #2a8ddf;
}

/* 下拉建议 */
.suggestion-list {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 6px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  max-height: 220px;
  overflow-y: auto;
  z-index: 100;
  padding: 6px 0;
  list-style: none;
}

.suggestion-list li {
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
}

.suggestion-list li:hover {
  background-color: #e6f7ff;
  color: #409eff;
  font-weight: 500;
}
</style>
